//
//  ViewController.m
//  TestDHlibxls
//
//  Created by David Hoerl on 1/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "FMDatabase.h"
#import "SandboxFile.h"
#import "xlsModel.h"
#import "DBDataFactory.h"
#import "Word.h"
#import "Audio.h"
#import "Picture.h"
#import "Relationship.h"
#import "Example.h"
#import "MyWords.h"
#import "History.h"

extern int xls_debug;

@implementation ViewController
{
	IBOutlet UITextView *textView;
}

@synthesize xlsList0 = _xlsList0;
@synthesize xlsList1 = _xlsList1;
@synthesize xlsList2 = _xlsList2;
@synthesize xlsList3 = _xlsList3;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [DBDataFactory sharedDBDataFactory].databasePath = @"wordsData.db";
    
    self.xlsList0 = [NSMutableArray array];
    self.xlsList1 = [NSMutableArray array];
    self.xlsList2 = [NSMutableArray array];
    self.xlsList3 = [NSMutableArray array];

	NSString *path = [SandboxFile GetPathForResource:@"demo.xls"]; // test.xls
    BOOL isExist = [SandboxFile IsFileExists:path];
    if (!isExist) {
        path = [SandboxFile GetPathForResource:@"demo.xls"];
    }
    
//	NSString *path = @"/tmp/test.xls";

	// xls_debug = 1; // good way to see everything in the Excel file
	
	_reader = [DHxlsReader xlsReaderFromFile:path];
	assert(_reader);

	NSString *text = @"";
	
	text = [text stringByAppendingFormat:@"AppName: %@\n", _reader.appName];
	text = [text stringByAppendingFormat:@"Author: %@\n", _reader.author];
	text = [text stringByAppendingFormat:@"Category: %@\n", _reader.category];
	text = [text stringByAppendingFormat:@"Comment: %@\n", _reader.comment];
	text = [text stringByAppendingFormat:@"Company: %@\n", _reader.company];
	text = [text stringByAppendingFormat:@"Keywords: %@\n", _reader.keywords];
	text = [text stringByAppendingFormat:@"LastAuthor: %@\n", _reader.lastAuthor];
	text = [text stringByAppendingFormat:@"Manager: %@\n", _reader.manager];
	text = [text stringByAppendingFormat:@"Subject: %@\n", _reader.subject];
	text = [text stringByAppendingFormat:@"Title: %@\n", _reader.title];
	
	text = [text stringByAppendingFormat:@"\n\nNumber of Sheets: %u\n", _reader.numberOfSheets];

#if 0
	[reader startIterator:0];
	
	while(YES) {
		DHcell *cell = [reader nextCell];
		if(cell.type == cellBlank) break;
		
		text = [text stringByAppendingFormat:@"\n%@\n", [cell dump]];
	}
#else
    [self readData:0 currentRow:2];
#endif
	textView.text = text;
}

- (xlsModel *)readData:(int)sheet currentRow:(int)row;
{
    NSMutableArray *tmpArr = [NSMutableArray array];
    for (int col = 1; col < 10; col++) {
        DHcell *cell = [_reader cellInWorkSheetIndex:sheet row:row col:col];
        [tmpArr addObject:cell];
    }
    
    xlsModel *model = [[xlsModel alloc] init];
    DHcell *tCell = (DHcell *)[tmpArr objectAtIndex:0];
    if (tCell.type == cellBlank) {
        return nil;
    }
    model.wordID = [tCell floatToStr];
    
    tCell = (DHcell *)[tmpArr objectAtIndex:1];
    model.level = [tCell floatToInt];
    
    model.word = ((DHcell *)[tmpArr objectAtIndex:2]).str;
    model.pinyin = ((DHcell *)[tmpArr objectAtIndex:3]).str;
    model.pos = ((DHcell *)[tmpArr objectAtIndex:4]).str;
    model.tranditional = ((DHcell *)[tmpArr objectAtIndex:5]).str;
    model.english = ((DHcell *)[tmpArr objectAtIndex:6]).str;
    model.example = ((DHcell *)[tmpArr objectAtIndex:7]).str;
    model.section = ((DHcell *)[tmpArr objectAtIndex:8]).str;
    NSLog(@"%@", model);
    return model;
}


- (void)readDataWhitSheet:(int)sheet startRow:(int)startRow count:(int)count
{
    [_xlsList0 removeAllObjects];
    [_xlsList1 removeAllObjects];
    [_xlsList2 removeAllObjects];
    [_xlsList3 removeAllObjects];
    for (int row = startRow; row < startRow + count; row++) {
        xlsModel *model = [self readData:sheet currentRow:row];
        if (model == nil) {
            break;
        }
        switch (sheet) {
            case 0:
               [_xlsList0 addObject:model]; 
                break;
            case 1:
                [_xlsList1 addObject:model];
                break;
            case 2:
                [_xlsList2 addObject:model];
                break;
            case 3:
                [_xlsList3 addObject:model];
                break;
                
            default:
                break;
        }
        
    }
}

- (IBAction)sheet0Action:(id)sender
{
    [self readDataWhitSheet:0 startRow:965 count:120];
    int i = 0;
    for (xlsModel *model in _xlsList0) {
        Example *example = [[Example alloc] init];
        example.sentenceID = [NSString stringWithFormat:@"%@1",model.wordID];
        example.sentence = model.example;
        [[DBDataFactory sharedDBDataFactory] insertIntoDB:example classType:[ExampleDAO class]];
        
        Word *word = [[Word alloc] init];
        word.wordID = model.wordID;
        word.word = model.word;
        word.pinyin = model.pinyin;
        word.tranditional = model.tranditional;
        word.english = model.english;
        word.pos = model.pos;
        word.section = model.section;
        word.samples = example.sentenceID;
        [[DBDataFactory sharedDBDataFactory] insertIntoDB:word classType:[WordDAO class]];
        i++;
    }
    NSLog(@"count: %d", i);
  
}

- (IBAction)sheet1Action:(id)sender
{
   [[DBDataFactory sharedDBDataFactory] searchWhere:nil orderBy:nil offset:0 count:10 classType:[AudioDAO class] callback:^(NSArray *result) {
       
   }];
    [[DBDataFactory sharedDBDataFactory] searchWhere:nil orderBy:nil offset:0 count:10 classType:[PictureDAO class] callback:^(NSArray *result) {
        
    }];
    [[DBDataFactory sharedDBDataFactory] searchWhere:nil orderBy:nil offset:0 count:10 classType:[RelationshipDAO class] callback:^(NSArray *result) {
        
    }];
    [[DBDataFactory sharedDBDataFactory] searchWhere:nil orderBy:nil offset:0 count:10 classType:[MyWordsDAO class] callback:^(NSArray *result) {
        
    }];
    [[DBDataFactory sharedDBDataFactory] searchWhere:nil orderBy:nil offset:0 count:10 classType:[HistoryDAO class] callback:^(NSArray *result) {
        
    }];
}

- (IBAction)sheet2Action:(id)sender
{
   [self readDataWhitSheet:2 startRow:1 count:100];
}

- (IBAction)sheet3Action:(id)sender
{
   [self readDataWhitSheet:3 startRow:1 count:100];
}

- (void)viewDidUnload
{
	textView = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end
